package com.example.zhihuijiaju;

import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.NetworkRequest;
import android.net.NetworkSpecifier;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiNetworkSpecifier;
import android.os.Bundle;
import android.os.PatternMatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;



public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    private static String Token;

    View Loading;

    RecyclerView recyclerView;

    MyRVAdapter myRVAdapter;
    List<Map<String, Object>> listitem;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Loading = findViewById(R.id.loading);
        recyclerView = findViewById(R.id.devices_item_view);
        //沉浸式状态栏
        SetStatusBar.setStatusBar(this, false, false);
        //凭证检查   查询状态
        token_check();
        //初始化设备列表
        InitList();
    }

    //按键回调
    public void onClick(View view) {
        Intent intent = new Intent();
        switch (view.getId())
        {
            case R.id.touxiang:Log.i(TAG,"登录");
                intent.setClass(MainActivity.this, Login.class);
                startActivityForResult(intent,Login.requestCode);
                overridePendingTransition(R.anim.bottomin_enter,R.anim.bottomout_exit);
                break;
            case R.id.jia:SetIotWIFI();break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.i(TAG, "String.valueOf(requestCode)+resultCode");
        Log.i(TAG, "requestCode:"+ requestCode+" "+"resultCode:"+ resultCode);

        if(requestCode == Login.requestCode&&resultCode == RESULT_OK) {
            Log.i(TAG,data.getStringExtra("token"));
        }
        if(requestCode == Add.requestCode&&resultCode == RESULT_OK){
            Log.i(TAG,data.getStringExtra("device"));
            JSONObject jsonObject =  JSON.parseObject(data.getStringExtra("device"));
            Map<String, Object> showitem = new HashMap<String, Object>();
            showitem.put("deviceId", jsonObject.get("deviceId"));
            showitem.put("CLIENT_ID", jsonObject.get("CLIENT_ID"));
            showitem.put("status", -1);
            listitem.add(showitem);
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            myRVAdapter.notifyItemInserted(myRVAdapter.getItemCount());
        }
    }

    //界面初始化
    private void InitList()
    {
        new Thread(){
            @Override
            public void run() {
                super.run();
                listitem = new ArrayList<Map<String, Object>>();
                try{
                    String devices = FileOperations.file_read(MainActivity.this,"devices");
                    Log.i(TAG, devices);

                    JSONObject jst=  JSONObject.parseObject(devices);
                    JSONArray jsonArray = new JSONArray(jst.getJSONArray("data"));


                    for (int i = 0; i < jsonArray.size(); i++) {
                        Log.i(TAG, String.valueOf(jsonArray.size()));
                        try {
                            JSONObject jsonObject =  jsonArray.getJSONObject(i);
                            Map<String, Object> showitem = new HashMap<String, Object>();
                            showitem.put("deviceId", jsonObject.get("deviceId"));
                            showitem.put("CLIENT_ID", jsonObject.get("CLIENT_ID"));
                            showitem.put("status", -1);
                            listitem.add(showitem);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }

                //设置线性适配器
                GridLayoutManager layoutManager = new GridLayoutManager(MainActivity.this,2);
                recyclerView.setLayoutManager(layoutManager);
                //设置列表默认动画效果
                recyclerView.setItemAnimator(new DefaultItemAnimator());
                //设置适配器
                myRVAdapter = new MyRVAdapter(MainActivity.this,listitem,Token);
                recyclerView.setAdapter(myRVAdapter);
            }
        }.start();
    }

    //凭证检查
    public void token_check(){
        //文件读取
        try {
            Token= FileOperations.file_read(this,"ToKen");
           // Log.i(TAG,"TOKEN:"+Token);
            if(Token.length()<10)
            {
                Intent intent = new Intent();
                intent.setClass(MainActivity.this, Login.class);
                startActivity(intent);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //设置返回按钮：不应该退出程序---而是返回桌面
    //复写onKeyDown事件
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent home = new Intent(Intent.ACTION_MAIN);
            home.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            home.addCategory(Intent.CATEGORY_HOME);
            startActivity(home);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
    //让用户连接过滤设备wifi
    private void SetIotWIFI()
    {
        WifiManager wifiManager = (WifiManager)
            this.getSystemService(Context.WIFI_SERVICE);
        if(!wifiManager.isWifiEnabled()){
            Toast.makeText(MainActivity.this,"请开启WIFI",Toast.LENGTH_SHORT).show();
            return;
        }
        NetworkSpecifier specifier = null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
            specifier = new WifiNetworkSpecifier.Builder()
                    .setSsidPattern(new PatternMatcher("Test", PatternMatcher.PATTERN_PREFIX))
                    // .setWpa2Passphrase("211211211")
                    .build();
            NetworkRequest request =
                    new NetworkRequest.Builder()
                            .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
                            .removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
                            .setNetworkSpecifier(specifier)
                            .build();


            ConnectivityManager connectivityManager = (ConnectivityManager)
                    getSystemService(Context.CONNECTIVITY_SERVICE);

            ConnectivityManager.NetworkCallback networkCallback = new ConnectivityManager.NetworkCallback() {
                @Override
                public void onAvailable(Network network) {
                    // do success processing here..
                    //TODO 连接OK，做些啥
                    Log.i(TAG,"wifi连接成功");
                    //使用当前连接wifi
                    connectivityManager.bindProcessToNetwork(network);
                    Intent intent = new Intent();
                    intent.setClass(MainActivity.this, Add.class);
                    startActivityForResult(intent,Add.requestCode);
                    overridePendingTransition(R.anim.bottomin_enter,R.anim.bottomin_exit);
                }

                @Override
                public void onUnavailable() {
                    // do failure processing here..
                    //TODO 连接失败，或者被用户取消了，做些啥
                    Log.i(TAG,"wifi连接失败");
                }
            };
            connectivityManager.requestNetwork(request, networkCallback);
        }
    }
}